let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');

let session = require('express-session');
let hash = require('pbkdf2-password')();

let bodyParser = require('body-parser');

let index = require('./routes/index');
let users = require('./routes/users');
let login = require('./routes/login');
let earth = require('./routes/earth');
let sql   = require('./routes/sql_api');
let test  = require('./routes/test');
let error_user = require('./routes/error_user');
let distribution = require('./routes/distribution');

let app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// app.use(express.urlencoded({ extended: false }));
app.use(session({
    resave: false,                 // don't save session if unmodified
    saveUninitialized: false,     // don't create session until something stored
    secret: 'shhhh, very secret'
}));

// Session-persisted message middleware
// simple logger for

  app.use(function(req, res, next){
      let err = req.session.error;
      let msg = req.session.success;
      delete req.session.error;
      delete req.session.success;
      res.locals.message = '';
      if (err) res.locals.message = '<p class="msg error">' + err + '</p>';
      if (msg) res.locals.message = '<p class="msg success">' + msg + '</p>';
      next();
  });


//dummy database

let usersList = {
    tj : {name:'tj'}
};

 hash({password:'lihao'},function(err,pass,salt,hash){
      if(err) throw err;
      usersList.tj.salt = salt;
      usersList.tj.hash = hash;
 });

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);
app.use('/login',login);
app.use('/earth',earth);
app.use('/sql',sql);
app.use('/test',test);
app.use('/distribution',distribution);
app.use('/error_user',error_user);

function authenticate(name,pass,fn){
    let user = usersList[name];

    if(!user) return fn(new Error('Cannot find user!'));

    hash({password:pass,salt:user.salt},function(err,pass,salt,hash){
         if(err) return fn(err);
         if(hash == user.hash) return fn(null,user)
    })
}

app.post('/login',function(req,res){
    console.log('name:',req.body.name);
    console.log('password:',req.body.password);
    authenticate(req.body.name,req.body.password,function(err,user){
        console.log('Result:',user);
        if(user){
            req.session.regenerate(function(){
                req.session.user = user;
                req.session.success = 'Authenticated as '+ user.name;
            });
             res.redirect('/');
        } else {
            req.session.error = 'Authentication failed, please check your '
                + ' username and password.'
                + ' (use "tj" and "foobar")';
            res.redirect('/error_user');
        }
    })
});



// catch 404 and forward to error handler
app.use(function(req, res, next) {
    let err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  // res.render('error');

    res.render('404error',{message:'Not Found 404'})     //页面
});

module.exports = app;
